﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DCT.AddIn.HostView;
using System.IO;
using System.Collections.ObjectModel;
using System.AddIn.Hosting;
using System.Xml.Linq;

namespace DCT.ViewModel
{
    public class AddInManagerViewModel : WorkspaceViewModel
    {
        private AddInManagerViewModel()
        {
            DisplayName = "AddInManager";
            _addInTokenList = new ObservableCollection<AddInToken>();
            _addInList = new List<DCTExtendedFunctionHostView>();
        }

        private ObservableCollection<AddInToken> _addInTokenList;
        private List<DCTExtendedFunctionHostView> _addInList;

        private static AddInManagerViewModel _instance;

        public static AddInManagerViewModel Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new AddInManagerViewModel();
                }

                return _instance;
            }
        }

        public ObservableCollection<AddInToken> AddInTokenList
        {
            get { return _addInTokenList; }
        }

        public List<DCTExtendedFunctionHostView> AddInList
        {
            get { return _addInList; }
        }
    }

    public class AutomationHost : HostObject
    {
        private DeviceMapViewModelRepository _deviceMapViewModelRepository;

        public AutomationHost(DeviceMapViewModelRepository deviceMapViewModelRepository)
        {
            _deviceMapViewModelRepository = deviceMapViewModelRepository;
        }

        public override Stream GetData()
        {
            MemoryStream dataStream = new MemoryStream();
            _deviceMapViewModelRepository.GetXMLSerializedData().Save(dataStream);
            //XmlSerializer s = new XmlSerializer(typeof(XElement));
            //s.Serialize(XmlWriter.Create(dataStream), root);
            dataStream.Flush();
            dataStream.Seek(0, SeekOrigin.Begin);
            return dataStream;
        }

        public override void ReportProgress(double progressPercent)
        {

        }

        public override void ApplyChanges(Stream xmlChanges)
        {
            XElement xmlData = XElement.Load(xmlChanges);
            _deviceMapViewModelRepository.ApplyChanges(xmlData);
        }
    }
}
